/*
 * @Author       : 吴豪
 * @Date         : 2021-12-4 15:56:22
 * @FilePath     : \book-manage-front\src\pages\userManage\usersComponents\EditUser.tsx
 * @Description  : 修改用户信息模态框
 */

import { saveUserInfo, getUserInfo, checkPhoneExist, deleterEnclosure } from '@/services/user';
import { serverUrl } from '@/utils/utils';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ProFormText, ProFormUploadButton } from '@ant-design/pro-form';
import { message, Modal } from 'antd';
import type { UploadFile } from 'antd/lib/upload/interface';
import React, { useRef, useState } from 'react';

type LayoutType = Parameters<typeof ProForm>[0]['layout'];

/**
 * 修改用户信息组件，将父级传来的数据解构，并实现修改用户信息功能
 * @param props
 * @returns
 */
const EditUser = (props: {
  isModalVisible?: any;
  isShowModal?: any;
  actionRef?: any;
  userAid?: any;
}) => {
  const { isModalVisible } = props;
  const { isShowModal } = props;
  const { actionRef } = props;
  const { userAid } = props;
  const [btn, setBtn] = useState<boolean>(false);
  const [formLayoutType] = useState<LayoutType>('horizontal');
  const [enclosureId, setEnclosureId] = useState<string>();
  const [delEnclosureId, setDelEnclosureId] = useState<boolean>(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  };

  /**
   * 获取要修改的用户信息
   * @param params
   * @returns
   */
  const getUserData = async () => {
    const param = {
      aid: userAid,
    };
    const response = await getUserInfo(param);
    setEnclosureId(response.enclosureId);
    if (response.enclosureId && response.enclosureName) {
      setFileList([{ uid: response.enclosureId, name: response.enclosureName }]);
    }

    return response;
  };

  const formRef = useRef<
    ProFormInstance<{
      name: string;
      phone: string;
      password: string;
    }>
  >();

  /**
   * 修改用户信息
   */
  const handleOk = async () => {
    const data = await formRef.current?.validateFields();
    const param = {
      aid: userAid,
      name: data?.name || '',
      phone: data?.phone || '',
      password: data?.password || '',
      enclosureId,
    };
    const response = await saveUserInfo(param);
    if (delEnclosureId) {
      const parms = {
        enclosureId: enclosureId!,
        aid: userAid,
      };
      await deleterEnclosure(parms);
      setEnclosureId(undefined);
    }
    if (response.status === undefined) {
      message.success('修改成功！');
      isShowModal(false);
      actionRef.current.reload();
    } else {
      message.error('修改失败！');
    }
  };

  return (
    <Modal
      destroyOnClose
      title={'修改用户'}
      width="649px"
      visible={isModalVisible}
      onOk={handleOk}
      okButtonProps={{ disabled: btn }}
      onCancel={() => {
        if (btn) {
          setBtn(false);
        }
        setEnclosureId(undefined);
        isShowModal(false);
      }}
    >
      <ProForm
        request={() => getUserData()}
        formRef={formRef}
        submitter={{
          submitButtonProps: {
            style: {
              display: 'none',
            },
          },
          resetButtonProps: {
            style: {
              display: 'none',
            },
          },
        }}
        {...layout}
        layout={formLayoutType}
        params={{}}
      >
        <ProFormText
          name="name"
          label="姓名"
          placeholder="请输入"
          rules={[
            {
              required: true,
              message: '请输入姓名',
            },
          ]}
        />
        <ProFormText
          name="phone"
          label="手机号码"
          placeholder="请输入"
          fieldProps={{
            //手机号的唯一性校验
            onBlur: async (event) => {
              const phone = event.target.value;
              if (phone) {
                const params = {
                  aid: userAid,
                  phone,
                };
                const response = await checkPhoneExist(params);
                if (response.isExist) {
                  message.error('该手机号已存在！');
                  setBtn(true);
                } else {
                  setBtn(false);
                }
              }
            },
          }}
          rules={[
            {
              required: true,
              message: '请输入手机号',
            },
            { pattern: new RegExp(/^1[3-9]\d{9}/g), message: '请输入11位正确的手机号' },
          ]}
        />
        <ProFormText.Password
          name="password"
          label="密码"
          placeholder="请输入"
          rules={[
            {
              required: true,
              message: '请输入密码',
            },
            {
              pattern: new RegExp(/^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,20}$/),
              message: '请输入6-20位字母+数字的密码，不能有空格！',
            },
          ]}
        />
        <ProFormUploadButton
          /**
           * 附件的覆盖上传，以及相关删除操作
           */
          name="file"
          label="上传附件"
          title="upload"
          max={1}
          listType="text"
          action={`${serverUrl()}/userManage/uploadEnclosure`}
          fieldProps={{
            maxCount: 1,
            defaultFileList: fileList,
            headers: {
              token: localStorage.getItem('token')!,
            },
            method: 'POST',
            onChange: (info) => {
              if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
              }
              if (info.file.status === 'done') {
                message.success(`${info.file.name} 已被修改！`);
                setEnclosureId(info.file.response.data.enclosureId);
                setDelEnclosureId(false);
              } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 修改失败！`);
              }
            },
            onRemove: async () => {
              setFileList([]);
              setDelEnclosureId(true);
            },
          }}
        />
      </ProForm>
    </Modal>
  );
};

export default EditUser;
